
from main import basedir
from flask import request
import time, os
from main.code import *
from main.utils import InterfaceHelper, RequestHelper, FileHelper, ImageHelper
from main.dbs.user_db import *
from flask_restplus import Api, Resource, fields
from . import api
# 定义命名空间
ns = api.namespace('user', description='User api')


user_model = api.model('UserModel', {
    'id': fields.Integer(readOnly=True, description='id'),
    'openid': fields.String(description='openid'),
    'message': fields.String(description='反馈信息'),
    'status': fields.Boolean(description='状态')
})


@ns.route('/code/<string:code>')
class UserApi(Resource):
    '''用户接口'''
    @ns.doc("get_user_id")
    @ns.marshal_with(user_model)
    def get(self, code):
        '''返回用户id'''
        info = InterfaceHelper.get_openid(code)
        if "errcode" in info:
            return fail(message="code is invalid")
        openid = info['openid']
        user = query_by_openid(openid)
        if user:
            return success(user.to_json())
        else:
            user = User(openid=openid)
            insert(user)
            user = query_by_openid(openid)
            return success(user.to_json(), False)
        return fail()





